package com.example.module_filemanage.MVVM.Module.QiNiu;

import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.example.module_base.Net.HttpClient;
import com.example.module_base.Net.ResponseHandler;
import com.example.module_filemanage.Interface.ICallBack;
import com.example.module_filemanage.Interface.IFileServer;
import com.example.module_filemanage.MVVM.Module.Business.TranModule;
import com.example.module_filemanage.MVVM.Module.Entil.Item_FileInfo_module;
import com.example.module_filemanage.MVVM.Module.Entil.Item_Left_Menu_Module;
import com.example.module_filemanage.Public.Constant;
import com.example.module_filemanage.Public.Data;
import com.example.module_filemanage.Utils.TimeTool;
import com.qiniu.storage.model.FileInfo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;

import static com.bumptech.glide.gifdecoder.GifHeaderParser.TAG;

/**
 * Created by SJ on 2018/4/18.
 */

public class FileManager {
    private static volatile FileManager mInstance;
    private static  int f1=0,f2=0,f3=0,f4=0,f=0;
    private static int spacecount;
    private Context mContext;
    private ICallBack mICallBack;
    private ProgressDialog mProgressDialog;
    private FileManager(Context context) {
        this.mContext=context;
    }
    public static FileManager getInstance(Context context) {
        if (mInstance == null) {
            synchronized (FileManager.class) {
                if (mInstance == null) {
                    mInstance=new FileManager(context);
                }
            }
        }
        return mInstance;
    }
    public void init(ICallBack callback,ProgressDialog progressDialog){
        this.mProgressDialog=progressDialog;
        f1=0;f2=0;f3=0;f=0;f4=0;
        mProgressDialog.setMessage("正在获取空间列表……");
        getBuckets();
        mICallBack=callback;

    }
    /**
     * 获取空间列表
     */
    public void getBuckets(){
        HttpClient<IFileServer> _httpClient=new HttpClient(mContext,TokenManager.getInstance().getManageToken(Constant.spaces+"\n"),IFileServer.class);
        Log.e("onSuccess", "onSuccess: ");
         Call<ArrayList<String>> _listCall=_httpClient.service(Constant.baseUrl,true).getBuckets();
        Log.e("onSuccess", "onSuccess: ");
        _httpClient.request(_listCall, new ResponseHandler<ArrayList<String>>() {
            @Override
            public void onSuccess(ArrayList<String> IO) {
                Log.e("onSuccess", "onSuccess: " +IO.get(0));
                Data.getInstance().SPACES=new ArrayList<>(IO);
                spacecount=IO.size();
                mProgressDialog.setMessage("正在获取空间相关信息……");
                getBucketsUrl(IO);
                getSpaceSize(IO);
                getSpaceFileCount(IO);
                getSpacesFileInfo(IO);
            }

            @Override
            public void onFailure(int code, String e) {
                Log.e("onfaile", "onfaile: " +e);
            }
        });
    }

    /**
     * 获取空间的域名
     * @param spaces
     */
    public void getBucketsUrl(final List<String> spaces){

        Data.getInstance().SPACESURL=new HashMap<>();
        for (int i=0; i < spaces.size(); i++) {
            final int j=i;
            HttpClient<IFileServer> _httpClient=new HttpClient(mContext,TokenManager.getInstance().getManageToken(Constant.spaceurl+"?tbl="+spaces.get(i)+"\n"),IFileServer.class);
            Call<ArrayList<String>> _listCall=_httpClient.service(Constant.baseUrl2,true).getBucketsUrl(spaces.get(i));
            _httpClient.request(_listCall, new ResponseHandler<ArrayList<String>>() {
                @Override
                public void onSuccess(ArrayList<String> IO) {

                    Data.getInstance().SPACESURL.put(spaces.get(j),IO.get(0));
                    Log.e(TAG, "onSuccess: 2" );
                    onCallBack(0);
                   // Log.e(TAG, "onSuccess: "+spaces.get(j)+"|"+IO.get(0) );
                }

                @Override
                public void onFailure(int code, String e) {
                    Log.e("onfaile", "onfaile: " +e);
                }
            });
        }

    }

    /**
     * 获取每个空间的存储大小
     * @param spaces
     */
    public void getSpaceSize(final List<String> spaces){
        Data.getInstance().SPACESIZE=new HashMap<>();

        for (int i=0; i < spaces.size(); i++) {
            final int j=i;
            String currenttime=TimeTool.getcurrentTime();
            String currentoldtime=TimeTool.getcurrentodTime();
            String url="?bucket="+spaces.get(i)+"&begin="+ currenttime+"&end="+currentoldtime+"&g=day";
            HttpClient<IFileServer> _httpClient=new HttpClient(mContext,TokenManager.getInstance().getManageToken(Constant.spacesize+url+"\n"),IFileServer.class);
            Call<ResponseBody> _listCall=_httpClient.service(Constant.baseUrl2,true).getSpaceSize(spaces.get(i),currenttime,currentoldtime,"day");
            _httpClient.request(_listCall, new ResponseHandler<ResponseBody>() {
                @Override
                public void onSuccess(ResponseBody IO) {

                    //Data.SPACESURL.put(spaces.get(j),IO.get(0));
                    try {
                        try {
                        //
                            JSONObject json=new JSONObject(IO.string());
                            JSONArray sizes=json.getJSONArray("datas");

                            Data.getInstance().SPACESIZE.put(spaces.get(j), sizes.getLong(sizes.length()-1));
                            onCallBack(1);
                          //  Log.e(TAG, "onSuccess: "+spaces.get(j)+"|"+String.valueOf(sizes.getLong(0)));
                        } catch (JSONException IE) {
                            IE.printStackTrace();
                        }


                    } catch (IOException IE) {
                        IE.printStackTrace();
                    }

                }

                @Override
                public void onFailure(int code, String e) {
                    Log.e("onfaile", "onfaile: " +e);
                }
            });
        }

    }
    /**
     * 获取每个空间的文件数量
     * @param spaces
     */
    public void getSpaceFileCount(final List<String> spaces){
        Data.getInstance().SPACEFILECOUNT=new HashMap<>();
        for (int i=0; i < spaces.size(); i++) {
            final int j=i;
            String currenttime=TimeTool.getcurrentTime();
            String currentoldtime=TimeTool.getcurrentodTime();
            String url="?bucket="+spaces.get(i)+"&begin="+ currenttime+"&end="+currentoldtime+"&g=day";
            HttpClient<IFileServer> _httpClient=new HttpClient(mContext,TokenManager.getInstance().getManageToken(Constant.spacefilecount+url+"\n"),IFileServer.class);
            Call<ResponseBody> _listCall=_httpClient.service(Constant.baseUrl2,true).getSpaceFileCount(spaces.get(i),currenttime,currentoldtime,"day");
            _httpClient.request(_listCall, new ResponseHandler<ResponseBody>() {
                @Override
                public void onSuccess(ResponseBody IO) {
                    //Data.SPACESURL.put(spaces.get(j),IO.get(0));

                    try {

                        try {
                            String ss=new String(IO.string());
                            JSONObject json=new JSONObject(ss);
                            JSONArray sizes=json.getJSONArray("datas");
                            Data.getInstance().SPACEFILECOUNT.put(spaces.get(j), sizes.getInt(sizes.length()-1));
                            onCallBack(2);
                            //Log.e(TAG, "onSuccess: "+spaces.get(j)+"|"+String.valueOf(sizes.getInt(0)));
                        } catch (JSONException IE) {

                            IE.printStackTrace();
                        }
                    } catch (IOException IE) {
                        IE.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int code, String e) {
                    Log.e("onfaile", "onfaile: " +e);
                }
            });
        }

    }
    /**
     * 获取每个空间的文件的信息
     */
    public void getSpacesFileInfo(final List<String> spaces){
        Data.getInstance().ALLFILEINFO=new ArrayList<>();
        for (int i=0; i <spaces.size() ; i++) {
            //列举空间文件列表
            final int j=i;
            new GetFileInfo(new ICallBack<List<Item_FileInfo_module>>() {
                @Override
                public void success(List<Item_FileInfo_module> items) {
                    Data.getInstance().ALLFILEINFO.addAll(items);
                    onCallBack(3);
                }
            }).execute(spaces.get(i));
        }
    }
    /**
     * 获取单个空间的文件的信息
     * @param spacename
     */
    public void getSpaceFileInfo(final String spacename,final ICallBack callback){
            //列举空间文件列表
            new GetFileInfo(new ICallBack<List<Item_FileInfo_module>>() {
                @Override
                public void success(List<Item_FileInfo_module> items) {
                    Collections.sort(items,new Comparator<Item_FileInfo_module>(){
                        public int compare(Item_FileInfo_module arg0, Item_FileInfo_module arg1) {
                            return -arg0.filetime.compareTo(arg1.filetime);
                        }
                    });
                    callback.success(items);
                }
            }).execute(spacename);
    }
/**==================================完成返回=================================*/
    public synchronized void onCallBack(int mode){
        switch (mode){
            case 0:
                f1++;
                if (f1==spacecount){
                    f++;
                    mProgressDialog.setMessage("获取空间域名完成！");
                }
                break;
            case 1:
                f2++;
                if (f2==spacecount){
                    f++;
                   // Log.e(TAG, "getSpaceSize1: " );
                    mProgressDialog.setMessage("获取空间文件存储大小完成！");
                }
                break;
            case 2:
                f3++;
                if (f3==spacecount){
                    f++;
                   // Log.e(TAG, "getSpaceSize2: " );
                    mProgressDialog.setMessage("获取空间文件数量完成！");
                }
                break;
            case 3:
                f4++;
                if (f4==spacecount){
                    f++;
                    // Log.e(TAG, "getSpaceSize2: " );
                    mProgressDialog.setMessage("获取每个文件信息完成！");
                }
                break;
        }
        if (f==4){
           // Log.e(TAG, "getSpaceSize33: " );
            mProgressDialog.setMessage("初始化完成！");
            mICallBack.success( TranModule.getitemleftmenumodule());

        }
    }
}
